# -*- encoding=utf-8 -*-

import logging
import subprocess
from build_log import Log

logger = Log()
fmt_logger = logging.getLogger("no_fmt")


def shell_cmd(cmd):
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, err = p.communicate()
    out = out.decode("utf-8", errors="ignore")
    out = out.strip()
    return out


def shell_cmd_live(cmd, cap_out=False, cap_err=False, verbose=False, cmd_verbose=True):
    """
    创建子进程执行命令，实时输出结果
    :param cmd: 命令
    :param cap_out: 是否捕捉输出结果
    :param cap_err:
    :param verbose:
    :param cmd_verbose: show cmd output to console, default not
    :return:
    """
    if cmd_verbose:
        logger.debug("exec cmd -- {}".format(cmd))

    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    out = []
    while True:
        if p.poll() is not None:
            break
        while True:
            line = p.stdout.readline()
            if line:
                line = line.decode("utf-8", errors="ignore")
                line = line.strip()
                _ = fmt_logger.info(line) if verbose else fmt_logger.debug(line)
                if cap_out and line and line != "\n":
                    out.append(line)
            else:
                break

    if cap_out:
        logger.debug("total {len(out)} lines output")

    ret = p.poll()

    err = None
    if ret:
        logger.debug("return code {}".format(ret))
        while True:
            line = p.stderr.readline()
            if not line:
                break
            err = line.decode("utf-8", errors="ignore").strip()
            _ = fmt_logger.error(err) if verbose else fmt_logger.debug(err)

    return ret, out, err if cap_err else None
